<template>
  <div class="doc-chunks-page">
    <div class="head">
      <el-button link type="primary" @click="$router.back()">返回</el-button>
      <h3>文档分块</h3>
      <div class="spacer"></div>
      <el-button type="primary" class="add-chunk-btn" @click="showAddDialog=true">
        <el-icon><Plus /></el-icon>
        <span>新增分块</span>
      </el-button>
    </div>
    <div class="doc-brief" v-if="docInfo">
      <span class="doc-name" :title="docInfo.doc_name">{{ docInfo.doc_name }}</span>
    </div>

    <el-table ref="chunksTable" :data="chunks" v-loading="loading" style="width: 100%" :max-height="tableMaxHeight">
      <el-table-column prop="chunk_index" label="ID" width="80"/>
      <el-table-column label="内容" min-width="400">
        <template #default="{ row }">
          <el-input
            v-if="editingIndex===row.chunk_index"
            v-model="editText"
            type="textarea"
            :autosize="{ minRows: 8, maxRows: 24 }"
            @keyup.enter="saveChunk(row)"
            @blur="saveChunk(row)"
          />
          <div v-else class="chunk-text" @dblclick="startEdit(row)">{{ row.chunk_text }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <template v-if="editingIndex!==row.chunk_index">
            <el-button size="small" type="primary" link @click="startEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" link @click="confirmDeleteChunk(row)">删除</el-button>
          </template>
          <template v-else>
            <el-button size="small" type="primary" :disabled="!canApply(row)" @click="saveChunk(row)">应用修改</el-button>
            </template>
        </template>
      </el-table-column>
    </el-table>

    <div class="pager">
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page="page"
        :page-size="pageSize"
        :total="total"
        @current-change="onPageChange"
      />
    </div>

    <el-dialog v-model="showAddDialog" title="新增分块" width="560px">
      <el-input v-model="newChunkText" type="textarea" :autosize="{minRows:8,maxRows:18}" placeholder="请输入分块内容" />
      <template #footer>
        <el-button @click="showAddDialog=false">取消</el-button>
        <el-button type="primary" :disabled="!trimmedNewChunk" :loading="adding" @click="createNewChunk">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { apiService } from '@/services/api'
import { ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

export default {
  name: 'DocumentChunks',
  components: { Plus },
  data() {
    return {
      docId: null,
      docInfo: null,
      chunks: [],
      page: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      editingIndex: null,
      editText: '',
      tableMaxHeight: 560,
      showAddDialog: false,
      newChunkText: '',
      adding: false
    }
  },
  computed: {
    trimmedNewChunk(){ return (this.newChunkText || '').trim() }
  },
  async mounted() {
    this.docId = Number(this.$route.params.docId)
    await this.loadDoc()
    this.fetch()
    this.$nextTick(() => {
      this.updateTableMaxHeight()
      window.addEventListener('resize', this.updateTableMaxHeight)
    })
  },
  unmounted() {
    window.removeEventListener('resize', this.updateTableMaxHeight)
  },
  methods: {
    async loadDoc(){
      try{ this.docInfo = await apiService.getDocument(this.docId) }catch(e){ this.docInfo = null }
    },
    async fetch() {
      this.loading = true
      try {
        const res = await apiService.getDocumentChunks(this.docId, this.page, this.pageSize)
        this.chunks = res.chunks || []
        this.total = res.total_count || 0
        this.$nextTick(this.updateTableMaxHeight)
      } catch (e) {
        // ignore
      } finally {
        this.loading = false
      }
    },
    onPageChange(p) {
      this.page = p
      this.fetch()
    },
    startEdit(row) {
      this.editingIndex = row.chunk_index
      this.editText = row.chunk_text
      this.$nextTick(this.updateTableMaxHeight)
    },
    async saveChunk(row) {
      if (this.editingIndex !== row.chunk_index) return
      const text = (this.editText || '').trim()
      if (!text || text === row.chunk_text) {
        this.editingIndex = null
        return
      }
      try {
        await apiService.updateChunk(this.docId, row.chunk_index, text)
        row.chunk_text = text
        this.$message.success('已更新')
      } catch (e) {
        // ignore
      } finally {
        this.editingIndex = null
        this.$nextTick(this.updateTableMaxHeight)
      }
    },
    async deleteChunk(row) {
      try {
        await apiService.deleteChunk(this.docId, row.chunk_index)
        this.$message.success('已删除')
        this.fetch()
      } catch (e) {
        // ignore
      }
    },
    async confirmDeleteChunk(row) {
      try {
        await ElMessageBox.confirm('确认删除该分块？', '提示', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await this.deleteChunk(row)
      } catch (_) { /* canceled */ }
    },
    async createNewChunk(){
      const text = this.trimmedNewChunk
      if (!text) return
      this.adding = true
      try{
        await apiService.createChunk(this.docId, text)
        this.$message.success('已添加')
        this.showAddDialog = false
        this.newChunkText = ''
        this.fetch()
      }catch(e){
        // ignore
      }finally{
        this.adding = false
      }
    },
    updateTableMaxHeight() {
      try {
        const tableEl = (this.$refs.chunksTable && this.$refs.chunksTable.$el) || this.$el.querySelector('.el-table')
        if (!tableEl) return
        const rect = tableEl.getBoundingClientRect()
        const viewportH = window.innerHeight || document.documentElement.clientHeight
        const bottomReserve = 110 // pager + 外边距
        const maxH = Math.max(240, viewportH - rect.top - bottomReserve)
        this.tableMaxHeight = maxH
      } catch (_) { /* ignore */ }
    },
    canApply(row) {
      return this.editingIndex === row.chunk_index && this.editText !== row.chunk_text
    }
  }
}
</script>

<style scoped>
.doc-chunks-page{ padding: 28px; --kb-accent: #4dabf7; --kb-accent-weak: rgba(77, 171, 247, 0.15); --kb-surface: linear-gradient(180deg, rgba(77,171,247,0.04), rgba(77,171,247,0.02)); background: var(--kb-surface); width: 100%; max-width: none; margin: 0; font-size: 14px; min-height: 0; }
.head{ display: flex; align-items: center; gap: 10px; margin-bottom: 8px; }
.head h3{ font-size: 20px; background-image: linear-gradient(120deg, rgba(77,171,247,0.35), rgba(77,171,247,0)); background-size: 100% 40%; background-repeat: no-repeat; background-position: 0 80%; }
.spacer{ flex: 1; }
.add-chunk-btn{ display: inline-flex; align-items: center; gap: 8px; height: 38px; padding: 0 18px; border-radius: 999px; font-weight: 700; box-shadow: 0 10px 24px rgba(61,85,236,.28); }
.add-chunk-btn :deep(.el-icon){ font-size: 16px; }
.add-chunk-btn:hover{ filter: brightness(1.05); box-shadow: 0 12px 28px rgba(61,85,236,.32); }
.doc-brief{ display:flex; align-items:center; gap:10px; margin-bottom: 12px; }
.doc-brief .doc-name{ font-weight: 800; font-size: 16px; }
.doc-brief .doc-meta{ font-size: 12px; color: var(--el-text-color-secondary); }
.chunk-text{ white-space: pre-wrap; line-height: 1.75; font-size: 14px; }

/* Table enhancement */
:deep(.el-table){ border-radius: 10px; overflow: hidden; }
:deep(.el-table__header th){ background: rgba(77,171,247,0.08); color: var(--el-text-color-primary); font-weight: 600; }
:deep(.el-table .cell){ font-size: 13.5px; }
:deep(.el-table__body tr:hover>td){ background-color: rgba(77,171,247,0.06) !important; }

.pager{ display: flex; justify-content: center; margin-top: 14px; }

/* Inputs focus/transition */
:deep(.el-input__inner), :deep(.el-textarea__inner){ font-size: 14px; }
:deep(.el-textarea__inner){ transition: border-color .24s ease, box-shadow .24s ease; }
:deep(.el-textarea__inner:focus){ border-color: var(--kb-accent); box-shadow: 0 0 0 3px rgba(77,171,247,0.12); }

/* Buttons */
:deep(.el-button){ transition: transform .18s ease, box-shadow .18s ease; }
:deep(.el-button--primary:hover){ box-shadow: 0 6px 14px rgba(64, 158, 255, 0.18); }

/* AI-style buttons */
.doc-chunks-page :deep(.el-button){
  background-color: var(--accent, var(--kb-accent));
  border: none;
  color: #ffffff;
  box-shadow: 0 6px 18px rgba(61,85,236,.25);
}
.doc-chunks-page :deep(.el-button:hover){ filter: brightness(1.05); }
.doc-chunks-page :deep(.el-button.is-link){
  background-color: var(--accent, var(--kb-accent));
  color: #ffffff;
  padding: 6px 12px;
  border-radius: 6px;
}
:deep(.el-popconfirm) .el-button--danger{ filter: brightness(0.95); }

/* Page entrance */
.doc-chunks-page{ animation: fadeIn .28s ease both; }
@keyframes fadeIn{ from{ opacity:0; transform: translateY(6px);} to{ opacity:1; transform: translateY(0);} }

/* Larger editing area */
:deep(.el-textarea__inner){
  font-size: 14px;
  line-height: 1.7;
}

/* Ensure table cell wraps nicely during editing */
:deep(.el-table .cell){
  white-space: normal;
}
</style> 